 #  Copyright 2010 Elmer Garduno
 #
 #  Licensed under the Apache License, Version 2.0 (the "License");
 #  you may not use this file except in compliance with the License.
 #  You may obtain a copy of the License at
 #
 #      http://www.apache.org/licenses/LICENSE-2.0
 #
 #  Unless required by applicable law or agreed to in writing, software
 #  distributed under the License is distributed on an "AS IS" BASIS,
 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 #  See the License for the specific language governing permissions and
 #  limitations under the License.

import os
import sys
import logging

from datetime import datetime

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))

import feedparser
import rest

class UserFeed(db.Model):
    user = db.UserProperty()
    url = db.URLProperty()

class Entry:
    pass

class MainPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
        logout = users.create_logout_url(self.request.uri)
        entries = self._fetch_feeds(user)
        template_values = {'entries': entries,
                           'logout': logout}
        path = os.path.join(os.path.dirname(__file__), 'feed.html')
        self.response.out.write(template.render(path, template_values))

    def _fetch_feeds(self, user):
        feeds = UserFeed.all()
        feeds.filter("user =", user)
        result = []
        for feed in feeds:
            result.extend(self._fetch_entries(feed.url))
        sortd = sorted(result, key=lambda entry: entry.date, reverse=True)
        procs = self._process_entries(sortd[:10])
        return procs
    
    def _fetch_entries(self, url):
        d = feedparser.parse(url)
        result = []
        for entry in d.entries:
            e = Entry()
            e.source = d.feed.title
            if entry.has_key('updated'):
                e.date = datetime(*entry.updated_parsed[0:6])
            else:
                e.date = datetime(*d.feed.date_parsed[0:6])
            e.title = entry.title.replace("'", "\\'")
            e.link = entry.link
            e.content = entry.summary
            result.append(e)
        return result

    def _process_entries(self, entries):
        for entry in entries:
            entry.terms = rest.term_extraction(entry.title + entry.content)
        return entries
              
class SubscriptionHandler(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
        feed = UserFeed()
        feed.user = user
        feed.url = self.request.get('url')
        feed.put()
        self.redirect('/')

class DeleteHandler(webapp.RequestHandler):
    def get(self, id):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
        db.delete(db.Key(id))
        self.redirect('/list')

class ListHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
        feeds = UserFeed.all()
        feeds.filter("user =", user)
        feed = UserFeed()
        result = []
        for feed in feeds:
            result.append((feed.key(), feed.url))
        template_values = {'feeds': result}
        path = os.path.join(os.path.dirname(__file__), 'list.html')
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/add', SubscriptionHandler),
                                      ('/list', ListHandler),
                                      (r'/delete/(.*)/', DeleteHandler)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
